package com.xusheng.cli.service.impl;

import com.xusheng.cli.common.base.MyPage;
import com.xusheng.cli.common.base.MyServiceImpl;
import com.xusheng.cli.entity.frontUserModule.WatchingRecord;
import com.xusheng.cli.entity.videoModule.Video;
import com.xusheng.cli.mapper.WatchingRecordMapper;
import com.xusheng.cli.service.WatchingRecordService;
import icu.mhb.mybatisplus.plugln.core.JoinLambdaWrapper;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * @author lyh
 * @since 2023-04-27 13:33
 */
@Service
public class WatchingRecordServiceImpl extends MyServiceImpl<WatchingRecordMapper, WatchingRecord> implements WatchingRecordService {

    @Override
    public MyPage<Video> watchingRecordList(long userId, long current, long size, Integer type) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startTime = null, endTime = null;
        if (type != null) {
            if (type == 1) {
                startTime = now.minusWeeks(1);
                endTime = now;
            } else if (type == 2) {
                startTime = now.minusMonths(1);
                endTime = now;
            } else if (type == 3) {
                endTime = now.minusMonths(1);
            } else if (type == 9) {
                startTime = now.with(LocalTime.MIN);
                endTime = now.with(LocalTime.MAX);
            }
        }
        JoinLambdaWrapper<WatchingRecord> wrapper = new JoinLambdaWrapper<>(WatchingRecord.class);
        wrapper.notDefaultSelectAll()
                .eq(WatchingRecord::getUserId, userId)
                .gt(startTime != null, WatchingRecord::getCreateTime, startTime)
                .lt(endTime != null, WatchingRecord::getCreateTime, endTime)
                .orderByDesc(WatchingRecord::getUpdateTime)
                .innerJoin(Video.class, Video::getId, WatchingRecord::getVideoId)
                .joinAnd(Video::getDeleted, false, 0)
                .selectAll()
                .end();
        MyPage<Video> page = baseMapper.joinSelectPage(new MyPage<>(current, size), wrapper, Video.class);
        page.getRecords().forEach(v -> {
            if (v.getSource() == 0) {
                v.setUrl(null);
            }
        });
        return page;
    }
}
